#!/bin/sh
# ./mf_deploy -s -d <db_name> -u <db_user> -p <db_pwd>
# -s update local svn sandbox

while getopts "sd:u:p:" opt; do
	case $opt in
		s) UPDATE="true";;
		d) DBNAME=$OPTARG;;
		u) USERNAME=$OPTARG;;
		p) PASSWORD=$OPTARG;;
		\?) echo "Invalid option: $OPTARG";;
	esac
done

echo "update: $UPDATE"
echo "database: $DBNAME"
echo "username: $USERNAME"
echo "password: $PASSWORD"

prj_path=/home/sam/Development/music-alms

echo "Stopping tomcat..."
#sudo service tomcat7 stop

sleep 1

if [ -n "$UPDATE" ]; then
    echo "Updating SVN..."
    /usr/bin/svn update "$prj_path"
    #/usr/bin/svn propset svn:ignore -R *.class $prj_path
    #/usr/bin/svn propset svn:ignore -R *.png $prj_path
else	
	##if [ "$1" != "svn" ]; then
	echo "No SVN update!"
fi

if [ -z "$DBNAME" ]; then
	echo "Not rebuilding database..."
else
	echo "Rebuilding database..."
	/usr/bin/mysql --user="$USERNAME" --password="$PASSWORD" --database="$DBNAME" --execute="source $prj_path""/sql/schema.sql;"
	/usr/bin/mysql --user="$USERNAME" --password="$PASSWORD" --database="$DBNAME" --execute="source $prj_path""/sql/load_data.sql;"
	sleep 1
fi

echo "Compiling MFServer..."
# did have ~/tomcat/webapps/mfservice/WEB-INF/classes/server, but guess pkg structure auto packages up server dir
# hence changed to deploy at classes/ dir level,  no javac -verbose
javac -Xmaxerrs 1 -d ~/Tomcat/webapps/mfservice/WEB-INF/classes/ "$prj_path/src/server/"*.java

echo "Copying web.xml..."
#cp "$prj_path/conf/web.xml" ~/Tomcat/webapps/mfservice/WEB-INF/

echo "Copying properties..."
#cp "$prj_path/properties/server.properties" ~/Tomcat/webapps/mfservice/WEB-INF/classes/properties/

echo "Clearing and removing logs..."
tomcat_logs=/var/log/tomcat7/
echo "" > $tomcat_logs"catalina.out"
#rm $tomcat_logs"manager.*"
#rm $tomcat_logs"localhost.*"
#rm $tomcat_logs"host-manager.*"
#rm $tomcat_logs"catalina.2014-*"
#rm $tomcat_logs"localhost_access_log.*"

echo "Starting tomcat..."
#sudo service tomcat7 restart
sleep 1

ts=$(ps -ef | grep tomcat | grep bootstrap.jar)
echo "$ts"

echo "music-alms server redeploy done"
